package com.dkd.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkd.client.order.OrderClient;
import com.dkd.dao.SkuClassDao;
import com.dkd.dao.SkuDao;
import com.dkd.entity.SkuClassEntity;
import com.dkd.entity.SkuEntity;
import com.dkd.entity.VendingMachineEntity;
import com.dkd.entity.VendoutRunningEntity;
import com.dkd.entity.dto.VmPageDto;
import com.dkd.entity.vo.SkuPageVo;
import com.dkd.entity.vo.SkuVo;
import com.dkd.service.SkuClassService;
import com.dkd.service.SkuService;
import com.dkd.service.VendingMachineService;
import com.dkd.service.VendoutRunningService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class SkuServiceImpl extends ServiceImpl<SkuDao, SkuEntity> implements SkuService {
    private final OrderClient orderClient;
    private final SkuDao skuDao;
    private final SkuClassDao skuClassDao;

    @Override
    public List<SkuVo> getTop10(Long businessId) {
        //获取商品售卖前10的id列表
        List<Long> skuIds = orderClient.getByBId(businessId);
        List<SkuEntity> skuEntities = skuDao.selectBatchIds(skuIds);

        return skuEntities.stream()
                .map(s -> new SkuVo(s.getSkuId(), s.getSkuName(), s.getSkuImage()))
                .collect(Collectors.toList());
    }

    @Override
    public SkuPageVo searchSku(VmPageDto vmPageDto) {
        Integer pageIndex = vmPageDto.getPageIndex();
        Integer pageSize = vmPageDto.getPageSize();
        String SkuName = vmPageDto.getName();
        Page<SkuEntity> page = new Page<>(pageIndex,pageSize);
        this.lambdaQuery().like(SkuName!=null,SkuEntity::getSkuName,SkuName).page(page);
        List<SkuEntity> records = page.getRecords();
        for (SkuEntity skuEntity : records) {
            SkuClassEntity skuClassEntity = skuClassDao.selectById(skuEntity.getClassId());
            if (skuClassEntity!=null){
                skuEntity.setSkuClass(skuClassEntity.getClassName());
            }
            skuEntity.setSkuClass("");
        }
        long totalCount = page.getTotal();
        long totaSize = totalCount / pageSize;
        return new SkuPageVo(pageIndex.toString(),
                pageSize.toString(),
                String.valueOf(totaSize),
                String.valueOf(totalCount),
                records);
    }

    @Override
    @Transactional
    @SneakyThrows
    public void upload(String fileName){
        //获取文件输入流
        FileInputStream inputStream = new FileInputStream(fileName);
        if (inputStream==null){
            inputStream.close();
            return;
        }
        XSSFWorkbook wb = new XSSFWorkbook(inputStream);

        Sheet sheet = wb.getSheetAt(0);//读取第一页
        int lastRowNum = sheet.getLastRowNum(); //获取最后一行的索引
        ArrayList<SkuEntity> skuEntities = new ArrayList<>();
        for (int i = 1; i <= lastRowNum; i++) {//从第二行开始读
            Row row = sheet.getRow(i);
            String stringSkuName = row.getCell(0).getStringCellValue();
            String stringSkuImage = row.getCell(1).getStringCellValue();
            int price = (int) row.getCell(2).getNumericCellValue();
            int classId = (int) row.getCell(3).getNumericCellValue();
            boolean isDisCount = Boolean.parseBoolean(row.getCell(4).getStringCellValue());
            String stringUnit = row.getCell(5).getStringCellValue();
            String stringBrandName = row.getCell(6).getStringCellValue();
            SkuEntity skuEntity = new SkuEntity();
            skuEntity.setSkuName(stringSkuName);
            skuEntity.setSkuImage(stringSkuImage);
            skuEntity.setPrice(price);
            skuEntity.setClassId(classId);
            skuEntity.setDiscount(isDisCount);
            skuEntity.setUnit(stringUnit);
            skuEntity.setBrandName(stringBrandName);
            skuEntities.add(skuEntity);
        }
        this.saveBatch(skuEntities);
        inputStream.close();
        wb.close();
    }


    public void upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            log.info("文件上传格式不正确");
            return;
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = null;
        Workbook wb = null;

        try {
            is = file.getInputStream();
        if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            Sheet sheet = wb.getSheetAt(0);//读取第一页
            int lastRowNum = sheet.getLastRowNum(); //获取最后一行的索引
            ArrayList<SkuEntity> skuEntities = new ArrayList<>();
            for (int i = 1; i <= lastRowNum; i++) {//从第二行开始读
                Row row = sheet.getRow(i);
                String stringSkuName = row.getCell(0).getStringCellValue();
                String stringSkuImage = row.getCell(1).getStringCellValue();
                int price = (int) row.getCell(2).getNumericCellValue();
                int classId = (int) row.getCell(3).getNumericCellValue();
                boolean isDisCount = Boolean.parseBoolean(row.getCell(4).getStringCellValue());
                String stringUnit = row.getCell(5).getStringCellValue();
                String stringBrandName = row.getCell(6).getStringCellValue();
                SkuEntity skuEntity = new SkuEntity();
                skuEntity.setSkuName(stringSkuName);
                skuEntity.setSkuImage(stringSkuImage);
                skuEntity.setPrice(price);
                skuEntity.setClassId(classId);
                skuEntity.setDiscount(isDisCount);
                skuEntity.setUnit(stringUnit);
                skuEntity.setBrandName(stringBrandName);
                skuEntities.add(skuEntity);
            }
            is.close();
            wb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
